package cn.ftx.result.handler;

import cn.ftx.result.data.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * <p>
 *     重写返回体
 * </p>
 *
 * @author AUTHER
 * @since 2021-04-29
 */
@Slf4j
@ControllerAdvice("cn.ftx.controller")
public class ResultResponseHandler implements ResponseBodyAdvice<Object> {

    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = requestAttributes.getRequest();
//        ResponseResult attribute = (ResponseResult) request.getAttribute(RESPONSE_RESULT_ANN);
//        return attribute == null ? false : true;
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("进入返回体，格式重写中");

        if (o instanceof Result){
            return o;
        }
        if (o instanceof String) {
            return JSON.toJSONString(Result.success(o));
        }

        return Result.success(o);
    }
}
